<script setup >
import { computed, reactive, ref } from 'vue';
import { editcateApi, addcateApi, getcateInfoApi } from '../../../api/cate'
import { ElMessage } from "element-plus";

const emit = defineEmits(["updateList"]);
// 表单数据
const defaultState = {
  catename: "",
  title: "",
  id:null
}
const formData = reactive({ ...defaultState });
// 验证规则
const formRules = {
  catename: [{ required: true, message: "分类名不能为空", trigger: "blur" }],
  title: [{ required: true, message: "请选择", trigger: "blur" }],
};
// 表单ref引用
const formRef = ref();
// 弹框控制变量
const isShow = ref(false);
// 关闭事件
const closeHandler = () => {
  // 移除校验
  formRef.value.resetFields()
  // 重置表单数据
  Object.assign(formData, { ...defaultState })
};
// 表单提交
const onSubmit = async () => {
  try {
    // 1. 校验数据
    await formRef.value.validate();
    // 2. 整理数据
    // 3. 提交数据
    const data = toRaw(formData);
    formData.id ? await editcateApi(data) : await addcateApi(data)
    // 4. 提示成功
    ElMessage.success("操作成功");
    // 5. 关闭
    isShow.value = false;
    // 6. 列表更新
    emit("updateList");
  } catch (error) {
    console.log(error);
  }
};
// 回显数据
const replyData = async (id) => {

  let res = await getcateInfoApi(id)
  console.log(res.data);
  Object.assign(formData,res.data)
  // formData:res.data.data.catename
  isShow.value = true
}
// 标题
const title = computed(() => {
  return formData.id ? '修改' : '新增'
})
defineExpose({
  isShow,replyData
});
</script>

<template>
  <el-dialog :title="title" v-model="isShow" width="45%" @close="closeHandler">
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px" :inline="false">
      <el-form-item label="分类名称" prop="catename">
        <el-input v-model="formData.catename"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="isShow = false">取消</el-button>
        <el-button @click="onSubmit" type="primary">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped></style>